/*
 * @Author: jiu yin
 * @Date: 2023-04-27 14:23:19
 * @LastEditTime: 2023-10-12 14:19:56
 * @LastEditors: jiu yin zhen jing
 * @FilePath: \ai-admin\src\comment\wangEditor\index.tsx
 * jiu
 */
import { useState, useEffect } from "react";
import "./index.scss";
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { Editor, Toolbar } from "@wangeditor/editor-for-react";
import { IDomEditor, IEditorConfig, IToolbarConfig } from "@wangeditor/editor";
type InsertFnType = (url: string, poster: string) => void
const WangEditor = (props: any) => {
   let {height,width}  = props
   // editor 实例
   const [editor, setEditor] = useState<IDomEditor | null>(null); // TS 语法
   // const [editor, setEditor] = useState(null)                   // JS 语法

   // 模拟 ajax 请求，异步设置 html
   //   useEffect(() => {
   //       setTimeout(() => {
   //           setHtml('<p>hello world</p>')
   //       }, 1500)
   //   }, [])

   // 工具栏配置
   const toolbarConfig: Partial<IToolbarConfig> = {}; // TS 语法


   // 编辑器配置
   const editorConfig: Partial<IEditorConfig> = {
      // TS 语法
      placeholder: "请输入内容...",
      MENU_CONF: {},
   };

   editorConfig.MENU_CONF["uploadImage"] = {
      server: import.meta.env.VITE_BASE_API + "/api/v1/media/upload",
      fieldName: "file",
      // 自定义插入图片
      customInsert(res: any, insertFn: InsertFnType) {
         // TS 语法
         console.log(res);

         // res 即服务端的返回结果
         // 从 res 中找到 url alt href ，然后插入图片
         insertFn(res.data.url);
      },
   };
   editorConfig.MENU_CONF['uploadVideo'] = {
    server: import.meta.env.VITE_BASE_API + "/api/v1/media/upload",
    fieldName: "file",
    // 自定义插入图片
    customInsert(res: any, insertFn: InsertFnType) {
       // TS 语法
       console.log(res);

       // res 即服务端的返回结果
       // 从 res 中找到 url alt href ，然后插入图片
       insertFn(res.data.url);
    },
}

   // 及时销毁 editor ，重要！
   useEffect(() => {
      return () => {
         if (editor == null) return;
         editor.destroy();
         setEditor(null);
      };
   }, [editor]);

   return (
      <>
         <div style={{ border: "1px solid #ccc", zIndex: 100 }}>
            <Toolbar
               editor={editor}
               defaultConfig={toolbarConfig}
               mode="default"
               style={{ borderBottom: "1px solid #ccc" }}
            />
            <Editor
               defaultConfig={editorConfig}
               value={props.html}
               onCreated={setEditor}
               onChange={editor => props.setHtml(editor.getHtml())}
               mode="default"
               style={{height:height||'520px',width:width||'99%', overflowY: "hidden" }}
            />
         </div>
         {/* <div style={{ marginTop: '15px' }}>
              {html}
          </div> */}
      </>
   );
};

export default WangEditor;
